package com.osdp.gateway.service.impl;

import com.google.common.collect.Maps;
import com.osdp.gateway.service.IPermissionService;
import com.osdp.gateway.util.CommonConstant;
import com.osdp.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Component
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Boolean hasAdminRole(String token) {
        List<String> roleCode = getRoleCodes(token);
        return roleCode.contains(CommonConstant.ROLE_SYSADMIN);
    }

    /**
     *
     * @param token
     * @return
     */
    public List<String> getRoleCodes(String token){
        String userId = JwtUtil.getUserId(token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Access-Token", token);
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
        String url = String.format("http://%s/uc/v1/rest/role/roleCodes?userId=%s", CommonConstant.UC_APP_NAME, userId);
        if(log.isInfoEnabled()){
            log.info("当前用户角色下访问URL： "+ url);
        }
        ResponseEntity<List> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
                List.class, Maps.newHashMap());//List is responseType, Map is uriVariables
        List<String> roleCode  = responseEntity.getBody();
        System.out.println("当前用户roleCode:　"+ roleCode);
        return roleCode;
    }
}
